#pragma once

#include <iostream>
#include <fstream>
#include <unordered_map>
#include <string>
#include <cstring>
#include "Log.hpp"

const std::string DefaultPath = "./Dict.txt";
const std::string sep = ": ";

class Dict
{
private:
    bool LoadDict()
    {
        std::ifstream in(_conf_filePath);
        if(!in.is_open())
        {
            LOG(FATAL, "open %s error", _conf_filePath.c_str());
            return false;
        }

        std::string line;
        while(std::getline(in, line))
        {
            if(line.empty()) continue;
            auto pos = line.find(sep);
            if(pos == std::string::npos) continue;
            std::string word = line.substr(0, pos);
            std::string chinese = line.substr(pos + sep.size());
            if(chinese.empty()) continue;
            LOG(DEBUG, "load info, %s : %s\n", word.c_str(), chinese.c_str());

            _dict.insert(std::make_pair(word, chinese));
            // _dict[word] = chinese;
        }
        in.close();
        LOG(DEBUG, "Load %s success\n", _conf_filePath.c_str());
        return true;
    }
public:
    Dict(const std::string& path = DefaultPath)
        :_conf_filePath(path)
    {
        // 读取文件内容
        if(LoadDict())
            perror("Load failed");
    }


    // 翻译功能
    std::string translate(const std::string& word, bool& trust)
    {
        trust = true;
        auto iter = _dict.find(word);
        if(iter == _dict.end())
        {
            trust = false;
            return "未找到";
        }
        return _dict[word];
    }

    ~Dict()
    {}
private:
    std::unordered_map<std::string, std::string> _dict; // 存放字典内容
    std::string _conf_filePath; // 文件名
};